(function (window, $, undefined) {
  'use strict';

  var dictData = {
    orderChannel: { //订单来源
      '1': '小程序',
      '2': '管理后台',
      '3': 'iOS',
      '4': '安卓'
    },
    orderType: {  //服务类型
      // '1': '立即接机',
      // '2': '立即接站',
      // '3': '预约接机',
      // '4': '预约接站',
      // '5': '预约送机',
      // '6': '预约送站',
      // '7': '预约用车',
      // '8': '立即用车'
    },
    bookModel: {  //车辆类型
      '1': '舒适型',
      '2': '商务7座',
      '3': '豪华轿车'
    },
    vehiclePurpose:{

    },
    payType: {  //支付类型     paymentType
      '1': '乘客支付',
      '2': '司机代付'
    },
    payChannel: { //支付渠道
      '1': '微信',
      '2': '支付宝',
      '3': '银联',
      '4': '账户扣款',
      '5': '企业代扣',
      '9': '其他'
    },
    orderState: { //订单状态
      '1': '等待接单',
      '2': '预约成功',
      '3': '已派车',
      '4': '司机出发',
      '5': '司机到达出发地',
      '6': '乘客已上车',
      '7': '行程中',
      '8': '行程结束待计算价格',
      '9': '行程结束待付款',
      '10': '标注已付款（用于司机代付）',
      '11': '已支付（确实已付款，来自支付渠道的返回结果）',
      '12': '已评价',
      '13': '已取消',
      '14': '派车失败下单失败',
      '15': '运力不足下单失败',
      '20': '已关闭',
      //字典返回的
      // '1':'等待接单',
      // '2':'预约成功',
      // '3':'已派车',
      // '4':'司机出发',
      // '5':'司机到达出发地',
      // '6':'乘客已上车',
      // '7': '行程中',
      // '8': '行程结束待计算价格',
      // '9': '行程结束待付款',
      // '10': '标注已付款（用于司机代付）',
      // '11': '已支付（确实已付款，来自支付渠道的返回结果）',
      // '12': '已评价',
      // '13': '已取消',
    },
    autoModelId:{

    },
    state:{
      '0': '离线',
      '1': '上线',
      '2': '待命',
      '3': '入栈中',
      '4': '入栈',
      '5': '服务中'
    }
  };

  var cityData = {};

  var orderData = {};

  var driverData = {};

  main(function () {


    //获取操作人并修改
    $("span[data-operator]").text(oUser.account)

    var $tableOrder = $('#table-order');
    util.jqGrid($tableOrder, {
      // url:'/json/order.json',
      url:ajaxURL.ORDER + '/order/getFinishOrderList',
      // datatype: 'json',
      autowidth: true,
      height: $(window).height() - 350,
      multiselect: true,
      multiboxonly: true,
      shrinkToFit: false,
      colModel: [
        // { name: 'orderNo', key: true, hidden: true },
        // { label: '编号', name: '', width: 50 },
        {
          label: '订单编号（ID）', key: true, name: 'orderNo', width: 150, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.orderNo + '">' + v + '</a>';
          }
        },
        { label: '创建时间', name: 'createTime', width: 150, formatter: function (v) {
          return util.dateFormat(v);
        } },
        { label: '用车时间', name: 'planDepartTime', width: 150, formatter: function (v) {
          return util.dateFormat(v);
        } },
        { label: '出发城市', name: 'planOrigCityId', width: 50, formatter: function (v) {
          return cityData[v] || '';
        } },
        {
          label: '服务类型', name: 'orderType', width: 80, formatter: function (v) {
          return dictData.orderType[v] || '';
        } },
        {
          label: '用车类型', name: 'bookModel', width: 80, formatter: function (v) {
          return dictData.bookModel[v] || '';
        } },
        { label: '车牌号', name: 'autoNo', width: 100 },
        { label: '下单人', name: 'placingUserPhone', width: 100 },
        { label: '用车人', name: 'passengerPhone', width: 100 },
        { label: '司机ID', name: 'driverId', width: 50 },
        { label: '司机电话', name: 'driverPhone', width: 100 },
        { label: '订单状态', name: 'orderState', width: 150, formatter: function (v) {
          return dictData.orderState[v] || '';
        } },
        { label: '支付类型', name: 'payType', width: 100, formatter: function (v) {
          return dictData.payType[v] || '';
        } },
        { label: '订单来源', name: 'orderChannel', width: 100, formatter: function (v) {
          return dictData.orderChannel[v] || '';
        } },
        {name:'orderState',hidden:true}
      ],
      loadComplete: function (res) {
        orderData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            orderData[item.orderNo] = item;
          });
        }
      },
      pager: '#pager-order'
    });



    // 字典下拉数据
    util.selectHtml('[name="orderType"]', dictData.orderType, '', '', '请选择');
    util.selectHtml('[name="bookModel"]', dictData.bookModel, '', '', '请选择');
    util.selectHtml('[name="orderChannel"]', dictData.orderChannel, '', '', '请选择');
    util.selectHtml('[name="payType"]', dictData.payType, '', '', '请选择');
    util.selectHtml('[name="payChannel"]', dictData.payChannel, '', '', '请选择');

    //订单状态
    util.getDict('orderState', 'orderState').then(function (data) {
      util.selectHtml('[name="orderState"]', data, 'value', 'name', '请选择');
      $.each(data, function (_, item) {
        dictData.orderState[item.value] = item.name;
      });
    });


    //订单类型
    util.getDict('orderType', 'orderType').then(function (data) {
      util.selectHtml('[name="orderType"]', data, 'value', 'name', '请选择');
      $.each(data, function (_, item) {
        dictData.orderType[item.value] = item.name;
      });
    });



    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      util.selectHtml($('[name="planOrigCityId"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        cityData[item.cityId] = item.name;
      });
      searchTable();
    });

    function searchTable() {
      var data = util.formData('#form-search');
      if (data.createTimeBegin) {
        data.createTimeBegin = util.getTimeStamp(data.createTimeBegin)
      }
      if (data.createTimeEnd) {
        data.createTimeEnd = util.getTimeStamp(data.createTimeEnd, true)
      }
      util.searchGrid($tableOrder, data);
    }

    $('#search-btn').click(searchTable)

    // 创建时间段
    laydate.render({
      range: '至',
      elem: '#created-time',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#created-time').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 里程时间段
    laydate.render({
      range: '至',
      elem: '#journey-time',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#journey-time').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    laydate.render({
      elem: '#plan_depart_time',
      type: 'datetime'
    });
    // 查看订单
    var $formOrderView = $('#form-order-view');
    $tableOrder.on('click', '.view', function () {
      var $this = $(this);
      var id = $this.data('id');
      // 根据 id 请求数据
      var data = $.extend(true, {}, orderData[id]);

      util.resetForm($formOrderView);

      data.bookModel = data.model;

      $formOrderView.find('[data-createTime]').text(util.dateFormat(data.createTime) || '');
      $formOrderView.find('[data-orderNo]').text(id);
      $formOrderView.find('#click-detail').attr('data-o', id)

      //时间处理
      data.paiedTime = util.dateFormat(data.paiedTime);
      data.destTime = util.dateFormat(data.destTime);

      //实际行驶时间
      if (data.driveTime) {
        data.driveTime = Math.floor(data.driveTime / 60) + ' 分钟';
      }

      //价格 里程格式处理
      data.planPrice = util.price(data.planPrice);
      data.factFinalPrice = util.price(data.factFinalPrice);
      // data.startMile = util.toKilometer(data.startMile);
      // data.endMile = util.toKilometer(data.endMile);
      data.waitMile = util.toKilometer(data.waitMile);

      util.fillForm($formOrderView, data);

      util.layerOpen({
        title: false,
        content: $('#layer-order-view'),
        area: ['1000px', '']
      });
    });

    // 取消订单
    $('#btn-cancel').click(util.oneCheck($tableOrder, function (id) {
      layer.confirm('确定取消该订单？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.tip.warn('取消操作...');
      });
    }));

    // 导出
    $('#btn-export').click(function () {
      util.tip.warn('导出操作...');
    });

    $('#order-save').click(function () {
      var _v = $validate.form();
      console.log(_v);
    });

    var $layerClickDetail = $('#layer-click-detail');
    $('#click-detail').click(function(){
      util.get(ajaxURL.PRICE + '/actualprice/getPriceActualPriceByOrderId?orderId=' + $(this).attr('data-o'), function (res) {
        var data = res.data;
        console.log(data);
        if (data) {
          util.mulPrice(data, [
            'serveiceCharge',   //路桥费
            'parkingFee',       //停车费
            'startFee',         //起步价
            'mileageMoney',     //里程费
            'timeFee',          //时长费
            'travelFee',        //远途费
            'eveFee',           //夜间服务费
            'cityFee',          //出城费
            'otherFee',         //其它费用
            'couponFee',        //代金券抵用
            'zero',             //抹零
            'totalFee'          //总计预估价
          ]);
          util.mulToKilmeter(data, [
            'mileage',          //里程数
            'kmLong',           //远途公里
          ]);
          // data.otherFee = data.otherFee + data.serveiceCharge + data.parkingFee;
          var hts = '';
          hts += '<p class="text-center text-primary text-uppercase">' + data.totalFee + '</p>';
          hts += '<p class="text-center text-uppercase"><span class="col-xs-4 col-xs-offset-2 text-left">起步价</span><span class="col-xs-4 text-right">' + data.startFee + '</span></p><p class="text-center">';
          hts += '<span class="col-xs-4 col-xs-offset-2 text-left">里程费<span>(' + data.mileage + ')</span></span><span class="col-xs-4 text-right">' + data.mileageMoney + '</span></p>';
          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">时长费<span>(' + Math.floor(data.time / 60) + ' 分钟)</span></span><span class="col-xs-4 text-right">' + data.timeFee + '</span></p>';
          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">远途费<span>('+data.kmLong+')</span></span><span class="col-xs-4 text-right">' + data.travelFee + '</span></p>';
          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">夜间服务费</span><span class="col-xs-4 text-right">' + data.eveFee + '</span></p>';
          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">出城费</span><span class="col-xs-4 text-right">' + data.cityFee + '</span></p>';

          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">停车费</span><span class="col-xs-4 text-right">' + data.parkingFee + '</span></p>';
          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">路桥费费</span><span class="col-xs-4 text-right">' + data.serveiceCharge + '</span></p>';

          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">其它费用</span><span class="col-xs-4 text-right">' + data.otherFee + '</span></p>';
          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">代金券已抵</span><span class="col-xs-4 text-right">' + data.couponFee + '</span></p>';
          hts += '<p class="text-center"><span class="col-xs-4 col-xs-offset-2 text-left">抹零</span><span class="col-xs-4 text-right">' + data.zero + '</span></p>';

          $('#layer-click-detail .d-container').html(hts)
        }
        else{
          $('#layer-click-detail .d-container').html('此订单无实付明细！')
        }
      })


      util.layerOpen({
        title:'车费详情',
        content:$layerClickDetail,
        area:['600px','400px']
      })
    })

  });




})(window, jQuery);
